import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class GeneralCalculatorScreen extends StatefulWidget {
  @override
  _GeneralCalculatorScreenState createState() =>
      new _GeneralCalculatorScreenState();
}

class _GeneralCalculatorScreenState extends State<GeneralCalculatorScreen> {
  // GlobalKey<FormState> 是一个全局唯一的键，用于在 Widget 树中标识和访问特定的 Form 组件。
  // 通过这个键，可以调用 Form 的状态方法（如 validate()、save()），从而实现表单验证、数据保存等功能。
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();
  final _rateController = TextEditingController();
  String _calculationResult = '';

  @override
  void dispose() {
    _amountController.dispose();
    _rateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('通用计算器'),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            // Form 是 Flutter 中的一个特殊的 Widget，用于组织表单控件，并提供验证、保存和重置等功能。
            // 通过将 GlobalKey<FormState> 传递给 Form，你可以从外部访问该 Form 的状态。这样就可以在任何地方调用它的验证方法，比如 validate()、save() 等。
            child: Form(
                key: _formKey,
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _buildTextFormField(
                        controller: _amountController,
                        labelText: '本金(元)',
                        icon: Icons.calculate,
                      ),
                      const SizedBox(height: 16),
                      _buildTextFormField(
                        controller: _rateController,
                        labelText: '年化利率(%)',
                        icon: Icons.percent,
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton.icon(
                          onPressed: _calculate,
                          icon: const Icon(Icons.calculate),
                          label: const Text('计算收益'),
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(vertical: 16.0),
                            textStyle: const TextStyle(fontSize: 18.0),
                          )),
                      const SizedBox(height: 16),
                      if (_calculationResult.isNotEmpty)
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Theme.of(context).colorScheme.surfaceVariant,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                                color: Theme.of(context).colorScheme.outline),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '计算结果',
                                style: Theme.of(context).textTheme.titleLarge,
                              ),
                              const Divider(height: 20),
                              Text(
                                _calculationResult,
                                style: Theme.of(context)
                                    .textTheme
                                    .bodyLarge
                                    ?.copyWith(height: 1.8),
                              ),
                            ],
                          ),
                        )
                    ]))));
  }

  TextFormField _buildTextFormField({
    required TextEditingController controller,
    required String labelText,
    required IconData icon,
    bool isNumber = false,
  }) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
        labelText: labelText,
        prefixIcon: Icon(icon),
        border: const OutlineInputBorder(),
      ),
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      inputFormatters: isNumber
          ? [FilteringTextInputFormatter.digitsOnly]
          : [FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}'))],
      // 验证输入 TextFormField 通过其 validator 属性来进行验证
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入$labelText';
        }
        return null;
      },
    );
  }

  void _calculate() {
    if (_formKey.currentState!.validate()) {
      final double? amount = double.tryParse(_amountController.text);
      final double? annualRate = double.tryParse(_rateController.text);

      if (amount == null || annualRate == null) {
        setState(() {
          _calculationResult = '请输入有效的数字';
        });
        return;
      }
      /// 先计算一年的总利息
      final double oneYearInterest = amount * annualRate / 100;
      /// 再将年利息分摊到每天（按一年 365 天计算）
      final double dailyInterest = oneYearInterest / 365;
      setState(() {
        _calculationResult =
            '一年总利息为 ${oneYearInterest.toStringAsFixed(2)} 元\n一天利息为 ${dailyInterest.toStringAsFixed(2)} 元。';
      });
    }
  }
}
